﻿using System;
using System.Collections;
using LiteNetLib;
using LiteNetLib.Utils;
using Script.UiSystem;
using SimpleTools.Json;
using SimpleTools.Net.SimpleServer.UDP;
using UnityEngine;

namespace Script.NetSystem.Core
{
    public abstract class BaseClient<T, TIt>
    {
        protected SimpleCilent<T> client;
        protected EventBasedNetListener netListener;
        
        public BaseClient()
        {
            
        }
        
        public BaseClient(int port, string userKey, ConnectSuccess onConnectSuccess, Action pollCallback = null,bool isJson = true)
        {
            netListener = new EventBasedNetListener();
            client = new SimpleCilent<T>(typeof(TIt), GetThisClient(), netListener, onConnectSuccess ,GetHandlerTypes(), isJson);
            client.Start(NetConst.Host, port, userKey);
            Debug.Log("connect : " + NetConst.Host + ":" + port + "to " + userKey);    
            var task = new Task(PollTask(pollCallback));
        }
        
        /// <summary>
        /// client 保持poll
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerator PollTask(Action pollCallback)
        {
            while (true)
            {
                pollCallback?.Invoke();
                client.Poll();
                yield return new WaitForSeconds(0.015f);
            }            
        }

        protected abstract Type[] GetHandlerTypes();

        protected abstract T GetThisClient();

        public virtual void CloseConnect()
        {
            client.Stop();
        }

        public virtual void ClientSend(JsonData jsonData)
        {
            client.Send(jsonData);
        }
        
    }
}